package com.cyx.netty.n6;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

/*
EventLoop IO任务

对应服务端类——EventLoopServer、EventLoopServer1
 */
public class EventLoopClient {
    public static void main(String[] args) throws InterruptedException {
        // 1.启动类
        Channel channel = new Bootstrap()
                // 2.添加EventLoop
                .group(new NioEventLoopGroup())
                // 3.选择客户端channel实现
                .channel(NioSocketChannel.class)
                // 4.添加handler
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override // 连接建立后被调用
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder()); // 将字符串转换成ByteBuf
                    }
                })
                // 5.连接到服务器
                .connect(new InetSocketAddress("localhost", 8888))
                .sync() // 阻塞方法，直到连接建立后才会往下运行
                .channel();
        for (int i = 1; i <= 10; i++) {
            channel.writeAndFlush("第" + i + "条数据");
        }
    }
}
